<template>
    <div>
        <el-dialog
            title="导入数据"
            :visible.sync="dialogVisible"
            v-dialogDrag
            @close="handleCancelDialog"
            width="900px"
            custom-class="excel-import-dialog"
            :close-on-click-modal="false">
            
            <!-- 步骤指示器 -->
            <div class="step-indicator">
                <div class="step-line"></div>
                <div 
                    v-for="(stepItem, index) in stepConfig" 
                    :key="index"
                    class="step-item"
                    :class="{
                        'active': step === index,
                        'completed': step > index
                    }">
                    <div class="step-icon">
                        <i v-if="step > index" class="el-icon-success"></i>
                        <span v-else>{{ index + 1 }}</span>
                    </div>
                    <div class="step-title">{{ stepItem.title }}</div>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="content-container">
                <!-- 步骤1: 选择导入方式 -->
                <div v-show="step === 0" class="step-content step-1">
                    <h3 class="step-heading">选择导入方式</h3>
                    <div class="import-type-selector">
                        <div 
                            class="type-card"
                            :class="{ 'active': importTp === 0 }"
                            @click="importTp = 0; handleChangeImportTp(0)">
                            <div class="type-icon">
                                <i class="el-icon-c-scale-to-original"></i>
                            </div>
                            <div class="type-content">
                                <h4>只录原始值需计算成果值</h4>
                                <p>导入模板只包含基础数据，中间值和成果值由系统计算得出</p>
                            </div>
                            <div class="type-check">
                                <i v-if="importTp === 0" class="el-icon-check"></i>
                            </div>
                        </div>
                        
                        <div 
                            class="type-card"
                            :class="{ 'active': importTp === 1 }"
                            @click="importTp = 1; handleChangeImportTp(1)">
                            <div class="type-icon">
                                <i class="el-icon-document"></i>
                            </div>
                            <div class="type-content">
                                <h4>录入所有值无需计算成果值</h4>
                                <p>导入模板包含所有数据，系统不会进行计算</p>
                            </div>
                            <div class="type-check">
                                <i v-if="importTp === 1" class="el-icon-check"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="import-info">
                        <h4><i class="el-icon-info"></i> 导入说明</h4>
                        <ul>
                            <li>1、选择"只录原始值需计算成果值"，导入模版的导入数据只包含了基础数，中间值和成果值由计算得出；选择“录入所有值无需计算成果值”，导入模版和导入数据都包含了中间值和成果值，程序不会进行计算，完全有导入文件数据</li>
                            <li>2、导入功能请先下载面板，按面板填写数据，导入功能会按照模板导入对应类型的数据</li>
                            <li>3、导入面板现在和数据导入是按照选择的电站生成和导入的</li>
                            <li>4、请填写有效的导入数据，以免造成无效数据、错误数据或者无法导入</li>
                        </ul>
                    </div>
                </div>
                
                <!-- 步骤2: 下载模板 -->
                <div v-show="step === 1" class="step-content step-2">
                    <div class="template-download">
                        <div class="download-status" :class="{ 'loading': tempLoad, 'ready': !tempLoad && tempLoad !== null }">
                            <div class="status-icon">
                                <i v-if="tempLoad" class="el-icon-loading"></i>
                                <i v-else class="el-icon-success"></i>
                            </div>
                            <div class="status-content">
                                <h4 v-if="tempLoad">正在生成模板，请稍候...</h4>
                                <h4 v-else>模板已生成成功！</h4>
                                <p v-if="!tempLoad && tempLoad !== null">
                                    请点击 <a :href="modelDownloadUrl" class="download-link">下载模板</a> 并按照模板格式填写数据
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 步骤3: 上传文件 -->
                <div v-show="step === 2" class="step-content step-3">
                    <div class="file-upload">
                        <el-upload
                            class="upload-area"
                            ref="upload"
                            drag
                            action=""
                            :limit="1"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :on-exceed="handleExceed"
                            :before-remove="beforeRemove"
                            :file-list="fileList"
                            :auto-upload="false"
                            :http-request="uploadFile">
                            <div class="upload-content">
                                <i class="el-icon-upload"></i>
                                <div class="upload-text">
                                    <p>将Excel文件拖到此处，或<em>点击上传</em></p>
                                    <p class="upload-tip">支持Excel文件，大小不超过10MB</p>
                                </div>
                            </div>
                        </el-upload>
                        
                        <div v-if="fileList.length > 0" class="file-preview">
                            <div class="file-item">
                                <i class="el-icon-document"></i>
                                <span class="file-name">{{ fileList[0].name }}</span>
                                <span class="file-size">{{ formatFileSize(fileList[0].size) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="dialog-footer">
                <el-button 
                    class="cancel-btn"
                    @click="step > 0 ? step-- : handleCancelDialog()" 
                    size="small" :icon="step == 0 ?'el-icon-circle-close' : 'el-icon-top'">
                    {{ step > 0 ? '上一步' : '取消' }}
                </el-button>
                
                <el-button 
                    type="primary" 
                    @click="handleNextStep" 
                    size="small"
                    :loading="loading"
                    class="confirm-btn"
                    :icon="step == 2 ? 'el-icon-upload' : 'el-icon-bottom'"
                    :disabled="step === 1 && tempLoad">
                    {{ getNextButtonText() }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { createTemp, SetImportPoint, importPointAllValues } from "@/api/https";
import { baseUrl } from '@/api/baseUrl';

export default {
    name: 'ExcelImport',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        stationId: {
            type: [String, Number],
            default: ''
        },
    },
    data() {
        return {
            loading: false,
            dialogVisible: this.visible,
            step: 0,
            importTp: 0,
            modelDownloadUrl: '',
            tempLoad: null,
            fileList: [],
            fd: {},
            stepConfig: [
                { title: '选择方式' },
                { title: '下载模板' },
                { title: '上传文件' }
            ]
        };
    },
    watch: {
        visible(newVal) {
            this.dialogVisible = newVal;
            if (newVal) {
                this.resetDialog();
            }
        },
        dialogVisible(newVal) {
            this.$emit('update:visible', newVal);
        }
    },
    methods: {
        resetDialog() {
            this.step = 0;
            this.importTp = 0;
            this.tempLoad = null;
            this.fileList = [];
            this.fd = {};
            this.modelDownloadUrl = '';
        },
        handleChangeImportTp(val) {
            this.importTp = val;
            this.modelDownloadUrl = `${baseUrl.httpUrl}/Instr/getTemp?stationID=${this.stationId}&tp=${this.importTp}`;
        },
        handleCancelDialog() {
            this.dialogVisible = false;
        },
        handleNextStep() {
            if (this.step === 0) {
                this.handleCreatTemp();
            } else if (this.step === 1) {
                this.step++;
            } else if (this.step === 2) {
                this.handleUpLoadExcel();
            }
        },
        getNextButtonText() {
            if (this.step === 0) return '下一步';
            if (this.step === 1) return '下一步';
            if (this.step === 2) return '导入数据';
            return '下一步';
        },
        handleCreatTemp() {
            this.step++;
            this.tempLoad = true;
            this.modelDownloadUrl = `${baseUrl.httpUrl}/Instr/getTemp?stationID=${this.stationId}&tp=${this.importTp}`;
            
            createTemp({
                stationID: this.stationId,
                tp: this.importTp
            }).then(res => {
                if (res.isSuccess) {
                    this.tempLoad = false;
                } else {
                    this.step--;
                    this.$message.error(res.errorMessage);
                }
            }).catch(error => {
                this.step--;
                this.$message.error('模板生成失败，请重试');
                console.error('模板生成错误:', error);
            });
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，请先移除已选文件`);
        },
        beforeRemove(file) {
            return this.$confirm(`确定移除 ${file.name}？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            });
        },
        handleUploadSuccess(res) {
            this.$message.success('文件上传成功！');
        },
        handleUploadError(res) {
            this.$message.error('文件上传失败！');
        },
        uploadFile(param) {
           const fileObj = param.file; 
           this.fd.append('files', fileObj)
        },
        handleUpLoadExcel() {
            this.loading = true;
            this.fd = new FormData();
            
            // 根据导入类型调用不同的API
            const apiCall = this.importTp === 0 ? this.onSetImportPoint : this.onImportPointAllValues;
            apiCall();
        },
        onSetImportPoint() {
            this.$refs.upload.submit();
            this.fd.append("STATION_ID", this.stationId);
            this.fd.append("style", '按监测仪器导航');
            
            SetImportPoint(this.fd).then(res => {
                this.loading = false;
                if (res.isSuccess) {
                    this.onCallBack(res.data);
                } else {
                    this.$message.error(res.errorMessage);
                }
            }).catch(error => {
                this.loading = false;
                this.$message.error('导入失败，请重试');
                console.error('导入错误:', error);
            });
        },
        onImportPointAllValues() {
            this.$refs.upload.submit();
            this.fd.append("STATION_ID", this.stationId);
            this.fd.append("style", '按监测仪器导航');
            
            importPointAllValues(this.fd).then(res => {
                this.loading = false;
                if (res.isSuccess) {
                    this.onCallBack(res.data);
                } else {
                    this.$message.error(res.errorMessage);
                }
            }).catch(error => {
                this.loading = false;
                this.$message.error('导入失败，请重试');
                console.error('导入错误:', error);
            });
        },
        onCallBack(data) {
            let errData = [], success = [], noData = [], 
                ErrorMessage = '', WarningMessage = '';
                
            if (data && data.length > 0) {
                data.forEach(item => {
                    if (item.state == -1) {
                        errData.push(item.message);
                        ErrorMessage += `<p style="line-height:30px">${item.message}</p>`;
                    } else if (item.state == 0) {
                        noData.push(item.message);
                        WarningMessage += `<p style="line-height:30px">${item.message}</p>`;
                    } else if (item.state == 1) {
                        success.push(item.state);
                    }
                });
            }
            
            if (errData.length > 0) {
                this.$message({
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                    message: ErrorMessage,
                    duration: 0,
                    showClose: true
                });
            } else if (noData.length > 0) {
                this.$message({
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                    message: WarningMessage,
                    duration: 0,
                    showClose: true
                });
            } else if (success.length > 0) {
                this.$message.success('数据导入成功！');
                this.dialogVisible = false;
                this.$emit('successImport');
            }
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    }
};
</script>

<style scoped lang="scss">
.excel-import-dialog {
    .step-indicator {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        margin-bottom: 30px;
        
        .step-line {
            position: absolute;
            top: 20px;
            left: 50px;
            right: 50px;
            height: 2px;
            background-color: #e4e7ed;
            z-index: 1;
        }
        
        .step-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
            flex: 1;
            
            &.active {
                .step-icon {
                    background-color: #409eff;
                    color: white;
                    border-color: #409eff;
                }
                
                .step-title {
                    color: #409eff;
                    font-weight: bold;
                }
            }
            
            &.completed {
                .step-icon {
                    background-color: #67c23a;
                    color: white;
                    border-color: #67c23a;
                }
                
                .step-title {
                    color: #67c23a;
                }
            }
            
            .step-icon {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background-color: white;
                border: 2px solid #e4e7ed;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 8px;
                transition: all 0.3s;
            }
            
            .step-title {
                font-size: 14px;
                color: #c0c4cc;
                transition: all 0.3s;
            }
        }
    }
    
    .content-container {
        min-height: 300px;
        padding: 0 20px;
        
        .step-heading {
            margin-top: 0;
            margin-bottom: 20px;
            color: #303133;
            font-size: 18px;
        }
        
        .step-1 {
            .import-type-selector {
                display: flex;
                flex-direction: column;
                gap: 15px;
                margin-bottom: 25px;
                
                .type-card {
                    display: flex;
                    align-items: center;
                    padding: 15px;
                    border: 1px solid #e4e7ed;
                    border-radius: 8px;
                    cursor: pointer;
                    transition: all 0.3s;
                    
                    &:hover {
                        border-color: #409eff;
                    }
                    
                    &.active {
                        border-color: #409eff;
                        background-color: #f0f7ff;
                    }
                    
                    .type-icon {
                        font-size: 24px;
                        color: #409eff;
                        margin-right: 15px;
                    }
                    
                    .type-content {
                        flex: 1;
                        
                        h4 {
                            margin: 0 0 5px 0;
                            color: #303133;
                        }
                        
                        p {
                            margin: 0;
                            color: #606266;
                            font-size: 13px;
                        }
                    }
                    
                    .type-check {
                        color: #67c23a;
                        font-size: 18px;
                    }
                }
            }
            
            .import-info {
                background-color: #f5f7fa;
                border-radius: 8px;
                padding: 15px;
                
                h4 {
                    margin: 0 0 10px 0;
                    color: #303133;
                    display: flex;
                    align-items: center;
                    
                    i {
                        margin-right: 5px;
                        color: #409eff;
                    }
                }
                
                ul {
                    margin: 0;
                    padding-left: 20px;
                    color: #606266;
                    
                    li {
                        margin-bottom: 5px;
                        line-height: 1.5;
                    }
                }
            }
        }
        
        .step-2 {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 250px;
            
            .template-download {
                text-align: center;
                
                .download-status {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    
                    &.loading .status-icon i {
                        color: #409eff;
                    }
                    
                    &.ready .status-icon i {
                        color: #67c23a;
                    }
                    
                    .status-icon {
                        font-size: 60px;
                        margin-bottom: 15px;
                    }
                    
                    .status-content {
                        h4 {
                            margin: 0 0 10px 0;
                            color: #303133;
                        }
                        
                        p {
                            margin: 0;
                            color: #606266;
                        }
                        
                        .download-link {
                            color: #409eff;
                            text-decoration: none;
                            
                            &:hover {
                                text-decoration: underline;
                            }
                        }
                    }
                }
            }
        }
        
        .step-3 {
            .file-upload {
                width:600px;
                .upload-area {
                     width:600px;
                    margin:40px 0 0 100px;
                    ::v-deep .el-upload-dragger {
                         width:600px;
                        height: 220px;
                        
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 2px dashed #dcdfe6;
                        border-radius: 8px;
                        transition: border-color 0.3s;
                        
                        &:hover {
                            border-color: #409eff;
                        }
                    }
                    
                    .upload-content {
                        text-align: center;
                        
                        i {
                            font-size: 50px;
                            color: #c0c4cc;
                            margin-bottom: 15px;
                        }
                        
                        .upload-text {
                            p {
                                margin: 5px 0;
                                color: #606266;
                                
                                em {
                                    color: #409eff;
                                    font-style: normal;
                                }
                            }
                            
                            .upload-tip {
                                font-size: 12px;
                                color: #909399;
                            }
                        }
                    }
                }
                
                .file-preview {
                    margin-top: 15px;
                    
                    .file-item {
                        display: flex;
                        align-items: center;
                        padding: 10px 15px;
                        background-color: #f5f7fa;
                        border-radius: 4px;
                        
                        i {
                            color: #409eff;
                            margin-right: 10px;
                        }
                        
                        .file-name {
                            flex: 1;
                            color: #303133;
                        }
                        
                        .file-size {
                            color: #909399;
                            font-size: 12px;
                        }
                    }
                }
            }
        }
    }
    
    .dialog-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #e4e7ed;
    }
}

@media (max-width: 768px) {
    .excel-import-dialog {
        width: 95% !important;
        
        .step-indicator {
            .step-item {
                .step-title {
                    font-size: 12px;
                }
            }
        }
        
        .content-container {
            padding: 0 10px;
        }
    }
}
</style>